/*
 * @Author: ljc
 * @Date: 2024-09-09 16:34:02
 * @LastEditors: g05047
 * @LastEditTime: 2025-03-19 13:39:53
 * @Description:
 */

import { ADD_BUTTON_ROW, ADD_RIGHT_BUTTON_ROW } from '@/components/dialogs/src/button-group-widget/components/cfg/button-table-constant.js'
import { watch, ref, reactive, nextTick } from 'vue';
import eventBus from '@/utils/event-bus';

// 方法前缀
const funcPrefix = 'func:'
/**
   * 执行用户自定义函数
   * @param {String} content 代码字符串
   * @param {Object} params 传入的参数对象
  **/
const executeVisbleFunction = (content, params, busiConfig) => {
    let result;
    try {
        if (content && content.startsWith(funcPrefix)) {
            const funcBody = content.replace(funcPrefix, '');
            let customFn = new Function('params', `${funcBody}`)
            const executeThis = { busiConfig }
            result = customFn.call(executeThis, params)
        }
        return result;
    } catch (error) {
        console.error('代码执行错误:', error);
    }
}
/**
 * 初始化数据
 */
const initTableData = (props, tableOptions) => {
    tableOptions.data = [
        ...props.fieldOptions || []
    ]
}
/**
* 获取表格数据
*/
const handleTableData = (tableRef, tableOptions) => {
    const { tableData } = tableRef.value?.getTableData()
    tableOptions.data = [
        ...tableData
    ]
}
/**添加行 */
const handleAddRow = async (tableRef, record, tableOptions, name) => {
    const { row: newRow } = await tableRef.value.insertAt(record, -1)
    await tableRef.value.setEditCell(newRow, name)
    handleTableData(tableRef, tableOptions)
}
/**
 * 删除
 */
const handleDelete = (tableRef, tableOptions) => {
    tableRef.value.removeCheckboxRow()
    handleTableData(tableRef, tableOptions)
}
/**
 * 左侧按钮组数据方法
 */
export const useRowHandle = ({ props, tableRef, tableOptions, codeDialogRef,
    codeDialogAttrs, busiConfig }) => {
    const tableEditInfo = reactive({
        row: null,
        column: null
    })
    initTableData(props, tableOptions)
    /**
    * 新增
    */
    const handleAdd = () => {
        const record = {
            ...ADD_BUTTON_ROW
        }
        handleAddRow(tableRef, record, tableOptions, 'name')
    }
    /**
     * 点击方法
     */
    const handleClick = (type) => {
        switch (type) {
            case 'add':
                handleAdd()
                break;
            case 'delete':
                handleDelete(tableRef, tableOptions)
                break;
            default:
                break;
        }
    }
    //用于兄弟组件接收事件
    eventBus.$on('defaultValue', row => {
        const data = tableRef.value?.getTableData()
        let tableData = data?.tableData ?? []
        if (tableData && tableData.length) {
            tableData.forEach(element => {
                if (row && row.value == element.value) {
                    element.default = true
                } else {
                    element.default = false
                }
            });
        }
    });
    // 编辑icon点击
    eventBus.$on('visibleFunc', ({ row, column }) => {
        codeEditorOpen(row, column)
    })
    // 编辑弹框打开
    const codeEditorOpen = (row, column) => {
        tableEditInfo.row = row
        tableEditInfo.column = column
        codeDialogAttrs.title = '隐藏配置'
        codeDialogAttrs.frontAlert = `column.${column.field} () {`
        codeDialogRef.value?.handleOpen(row[column.field])
    }
    // 编辑弹框确认回调
    const handleCodeEditorConfirm = (content) => {
        const { row, column } = tableEditInfo
        row[column.field] = content
        let params = {}
        const result = executeVisbleFunction(content, params, busiConfig)
        tableOptions.data.forEach(element => {
            if (element.value === row.value) {
                element.visible = result
            }
        });
    }

    // 监听数据源变化
    watch(() => tableOptions.data,
        (newData) => {
            eventBus.$emit('buttonGroupData', newData);
        },
        { deep: true, immediate: false }
    )
    return {
        handleClick,
        handleCodeEditorConfirm
    }
}
/**
 * 右侧按钮组数据方法
 */
export const useRightRowHandle = ({ props, tableRef, tableOptions }) => {
    initTableData(props, tableOptions)
    /**
    * 新增
    */
    const handleAdd = () => {
        const record = {
            ...ADD_RIGHT_BUTTON_ROW
        }
        handleAddRow(tableRef, record, tableOptions, 'name')
    }
    /**
     * 点击方法
     */
    const handleClick = (type) => {
        switch (type) {
            case 'add':
                handleAdd()
                break;
            case 'delete':
                handleDelete(tableRef, tableOptions)
                break;
            default:
                break;
        }
    }
    // 监听数据源变化
    watch(() => tableOptions.data,
        (newData) => {
            eventBus.$emit('rightButtonData', {
                data: newData,
                buttonCurrentValue: props.optionModel.buttonCurrentValue
            },);
        },
        { deep: true, immediate: false }
    )
    return {
        handleClick,
        initTableData,
    }
}

